﻿using AntdUI;
using FreeSql.Internal;
using MySqlX.XDevAPI.Common;
using Org.BouncyCastle.Utilities.Collections;
using PosClient.Helper;
using PosClient.Interfaces;
using PosClient.Model;
using PosClient.Service;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Text;
using System.Threading.Tasks;

namespace PosClient.View.Login.ViewModel
{
    public class LoginViewModel: ReactiveObject
    {
        private IScheduler _mainScheduler;

        #region 属性

        [Reactive]
        public string Username { get; set; }

        [Reactive]
        public string Password { get; set; }

        /// <summary>
        /// 联网状态
        /// </summary>
        public bool Connected { get; set; }

        [Reactive]
        public bool HasInit { get; set; } = true;

        #endregion

        #region Command

        /// <summary>
        /// 登录
        /// </summary>
        public ReactiveCommand<Unit, Result<User>> LoginCommand { get; }

        /// <summary>
        /// 初始化
        /// </summary>
        public ReactiveCommand<Unit, Result<string>> LoadingCommand { get; }

        /// <summary>
        /// 数据库同步
        /// </summary>
        public ReactiveCommand<Unit, Result<string>> DbCommand { get; }

        /// <summary>
        /// 门店配置
        /// </summary>
        public ReactiveCommand<Unit, Result<string>> PosCommand { get; }

        /// <summary>
        /// 用户配置
        /// </summary>
        public ReactiveCommand<Unit, Result<string>> UserCommand { get; }

        /// <summary>
        /// 基础配置
        /// </summary>
        public ReactiveCommand<Unit, Result<string>> SetCommand { get; }
        #endregion

        public LoginViewModel(IScheduler mainScheduler)
        {
            _mainScheduler = mainScheduler;

            var canLogin = this
            .WhenAnyValue(
                vm => vm.Username,
                vm => vm.Password,
                (user, password) => !string.IsNullOrWhiteSpace(user) && !string.IsNullOrWhiteSpace(password));

            LoginCommand = ReactiveCommand.Create(LoginCommandImpl, canLogin, mainScheduler);
            LoadingCommand = ReactiveCommand.Create(LoadingCommandImpl);
            DbCommand = ReactiveCommand.Create(DbCommandImpl);
            PosCommand = ReactiveCommand.Create(PosCommandImpl);
            UserCommand = ReactiveCommand.Create(UserCommandImpl);
            SetCommand = ReactiveCommand.Create(SetCommandImpl);

            Connected = DataUtil.CheckNetWorkConnection();
        }



        private Result<User> LoginCommandImpl()
        {
            Result<User> result = new Result<User>
            {
                Message = "账号或者密码错误",
                Success = false
            };
            using (var conn = FreeClient.Sqlite)
            {
                Logger.AuditLogger.Audit($"登录系统 {Username}");
                var posList = conn.Queryable<Pos>().ToList();
                if (posList == null || posList.Count == 0)
                {
                    result.Success = false;
                    result.Message = "未注册，请注册";
                }
                else
                {
                    var pos = posList.Where(x => x.StoreCode == Globals.StoreCode && x.PosNo == Globals.Pos && x.Status == 1).First();
                    if (pos == null)
                    {
                        result.Success = false;
                        result.Message = "POS配置不正确";
                    }
                    else
                    { 
                        var user = conn.Queryable<User>().Where(x => x.Username == Username && x.Password == Password).ToList().FirstOrDefault();
                        if (user == null)
                        {
                            result.Success = false;
                            result.Message = "用户名或者密码错误";
                        }
                        else
                        {
                            if (user.Status != 1)
                            {
                                result.Success = false;
                                result.Message = "账号已禁用";
                            }
                            else
                            {
                                result.Success = true;
                                result.Message = "登录成功";

                                Locator.CurrentMutable.RegisterLazySingleton<IPluService>(() => new PluService());

                                conn.Update<User>()
                                    .Set(it => it.LastLoginTime == DateTime.Now)
                                    .Where(it => it.Username == user.Username)
                                    .ExecuteAffrows();
                                Globals.Username = user.Username;
                                string nowDate = DateTime.Now.ToString("yyyy-MM-dd");
                                if (pos.BalanceDate == null)
                                {
                                    pos.BalanceDate = Convert.ToDateTime(DateTime.Now.ToString("D").ToString());
                                }
                                string balanceDate = pos.BalanceDate.ToString("yyyy-MM-dd");
                                if (balanceDate != nowDate)
                                {
                                    pos.BalanceDate = Convert.ToDateTime(DateTime.Now.ToString("D").ToString());
                                    conn.Update<Pos>()
                                        .Set(it => it.BalanceDate == pos.BalanceDate)
                                        .Where(it => it.StoreCode == pos.StoreCode && it.PosNo == pos.PosNo)
                                        .ExecuteAffrows();
                                }
                                Globals.BalanceDate = pos.BalanceDate;
                            }
                        }
                    }
                }
            }
            return result;
        }

        private Result<string> LoadingCommandImpl()
        {
            Result<string> result = new Result<string>
            {
                Message = "请求成功",
                Success = true
            };
            result = DbCommandImpl();
            if (result.Success)
            {
                result = PosCommandImpl();
                if (result.Success)
                {
                    result = UserCommandImpl();
                    if (result.Success)
                    {
                        result = SetCommandImpl();
                    }
                }
            }
            return result;
        }

        private Result<string> DbCommandImpl()
        {
            Result<string> result = new Result<string>
            {
                Message = "请求成功",
                Success = true
            };
            try
            {
                using (var conn = FreeClient.Sqlite)
                {
                    conn.CodeFirst.SyncStructure<Order>();
                    conn.CodeFirst.SyncStructure<OrderItem>();
                    conn.CodeFirst.SyncStructure<OrderPay>();

                    conn.CodeFirst.SyncStructure<Pos>();
                    conn.CodeFirst.SyncStructure<User>();

                    conn.CodeFirst.SyncStructure<JobEntity>();
                    conn.CodeFirst.SyncStructure<Seq>();
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = $"数据库结构同步：{ex.Message}";
            }
            return result;
        }

        private Result<string> PosCommandImpl()
        {
            Result<string> result = new Result<string>
            {
                Message = "请求成功",
                Success = true
            };
            using (var conn = FreeClient.Sqlite)
            {
                var posList = conn.Select<Pos>().Where(x => x.Status == 1).ToList();
                //联网
                if (Connected)
                {
                    if (posList != null && posList.Count > 0)
                    {
                        var pos = posList.FirstOrDefault();
                        InitGlobals(pos);
                    }
                    else
                    {
                        //用接口请求数据，缓存并修改到本地数据库
                        Pos pos = new Pos()
                        {
                            StoreCode = "440103",
                            StoreName = "广州珠江新城店",
                            PosNo = "0001",
                            Status = 1,
                            BalanceDate = DateTime.Now,
                            Account = "440103"
                        };
                        var count = conn.Insert(pos).ExecuteAffrows();
                        if (count > 0)
                        {
                            InitGlobals(pos);
                        }
                        else
                        {
                            result.Success = false;
                            result.Message = "初始化数据失败";
                        }
                    }
                }
                else
                {
                    //用接口请求数据，缓存并修改到本地数据库
                    Pos pos = new Pos()
                    {
                        StoreCode = "440103",
                        StoreName = "广州珠江新城店",
                        PosNo = "0001",
                        Status = 1,
                        BalanceDate = DateTime.Now,
                        Account = "440103"
                    };
                    var count = conn.Insert(pos).ExecuteAffrows();
                    if (count > 0)
                    {
                        InitGlobals(pos);
                    }
                    else
                    {
                        result.Success = false;
                        result.Message = "初始化数据失败";
                    }
                }
            }
            return result;
        }

        private Result<string> UserCommandImpl()
        {
            Result<string> result = new Result<string>
            {
                Message = "请求成功",
                Success = true
            };
            using (var conn = FreeClient.Sqlite)
            {
                if (Connected)
                {
                    //联网先删后存
                    var users = conn.Select<User>().Where(x => x.Status == 1).ToList();
                    if (users.Count > 0)
                    {

                    }
                    else
                    {
                        User user = new User()
                        {
                            Username = "admin",
                            Password = "admin",
                            NickName = "admin",
                            LastLoginTime = DateTime.Now,
                            Status = 1
                        };
                        conn.Insert(user).ExecuteAffrows();
                    }
                }
                else
                {
                    User user = new User()
                    { 
                        Username = "admin",
                        Password = "admin",
                        NickName = "admin",
                        LastLoginTime = DateTime.Now,
                        Status = 1
                    };
                    conn.Insert(user).ExecuteAffrows();
                }
            }
            return result;
        }

        private Result<string> SetCommandImpl()
        {
            Result<string> result = new Result<string>
            {
                Message = "请求成功",
                Success = true
            };

            return result;
        }

        private void InitGlobals(Pos pos)
        {
            if (pos != null)
            {
                Globals.StoreCode = pos.StoreCode;
                Globals.StoreName = pos.StoreName;
                Globals.Pos = pos.PosNo;
                Globals.Account = pos.Account;
                Globals.ACCESS_TOKEN = pos.AccessToken;
                Globals.Version = pos.Version;
            }
        }
    }
}
